<?php
/**
 * Created by PhpStorm.
 * User: VMU
 * Date: 2017/3/6
 * Time: 14:22
 */

namespace App\Channels;

use EasyWeChat\Foundation\Application;
use EasyWeChat\Message\News;
use Illuminate\Notifications\Notification;

use EasyWeChat\Core\Exceptions\HttpException;

use Exception;

class WechatChannel
{

    protected $wechat;

    public function __construct(Application $wechat)
    {
        $this->wechat = $wechat;
    }

    /**
     * 微信发送通道
     * @param $notifiable
     * @param Notification $notification
     */
    public function send($notifiable, Notification $notification)
    {

        try {
            $message = $notification->toWechat($notifiable);
            $openid = $this->getOpenid($notifiable);
//            dd($message);
            if(!$openid) {
                \Log::error('发送微信模板消息失败：openid为空！');
                return false;
            }

            if(!$message['template_id']) {
                \Log::error('发送微信模板消息失败：模板消息ID为空！');
                return false;
            }

            //发送模板消息
            $rt = $this->wechat->notice->send([
                'touser' => $openid,
                'template_id' => data_get($message, 'template_id'),
                'data' => data_get($message, 'data'),
                'url' => data_get($message, 'url'),
            ]);

            if($rt->errcode!=0){
                \Log::error('发送微信模板消息失败！'.var_export($rt,true));
            }

        } catch (Exception $e) {
            \Log::error('发送微模板消息异常！'.$e->getMessage());
        }
    }

    protected function getOpenid($notifiable) {
        if(!$notifiable) {
            throw new \Exception('微信通知对象notifiable不存在！');
        }
        if($openid = $notifiable->routeNotificationFor('slack') ) {
            return $openid;
        }
        return $notifiable->openid;
    }
}